
package com.sailing.lianxi.thread.pool;

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 
 * 类名称：FixedThreadPoolTest
 * 类描述：FixedThreadPool线程池测试
 * 创建人：wanggang
 * 创建时间：2018年5月7日 下午4:09:53
 * 修改人：wanggang
 * 修改时间：2018年5月7日 下午4:09:53
 * 修改备注：
 */
public class FixedThreadPoolTest {
    public static void t1(){
        int threadNum = Runtime.getRuntime().availableProcessors();//线程核数
        System.out.println("coreNum="+threadNum);
        ExecutorService pool = Executors.newFixedThreadPool(threadNum);
        for(int i=0;i<10;i++){
            //线程使用外部变量需要加final
            final int index = i;
           Runnable synRunnable = new Runnable() {
                public void run() {
                    long start = System.currentTimeMillis();
                    System.out.println("线程:"+Thread.currentThread().getName()+",索引="+index);
                    try {
                    	//执行业务逻辑
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }  
                    System.out.println("线程："+Thread.currentThread().getName()+",耗时(s)："+(System.currentTimeMillis()-start)/1000);
                }
            };
            pool.submit(synRunnable);
        }
    }
    public static void t2(){
      
    	for(int i=0;i<5;i++) {
    		new Thread(new Runnable() {
    			ExecutorService pool = Executors.newFixedThreadPool(4);
    		    final long awaitTime = 5 * 1000;
				int i = 0;
				public void run() {
//				    final CyclicBarrier barrier  = new CyclicBarrier(4,new Runnable() {
//                        @Override
//                        public void run() {
//                            System.out.println("插入数据");
//                            
//                        }
//                    });
					while(true) {
					 // 当前排队线程数
					    int queueSize = ((ThreadPoolExecutor)pool).getQueue().size();
					    // 当前活动线程数
	                    int activeCount = ((ThreadPoolExecutor)pool).getActiveCount();
//						System.out.println(Thread.currentThread().getName()+"========================="+i);
	                    long completedTaskCount = ((ThreadPoolExecutor)pool).getCompletedTaskCount();
	                    // 总线程数（排队线程数 + 活动线程数 +  执行完成线程数） 
	                    long taskCount = ((ThreadPoolExecutor)pool).getTaskCount();
//	                    System.out.println("taskCount="+taskCount);
				           Runnable synRunnable = new Runnable() {
				                public void run() {
				                    long start = System.currentTimeMillis();
				                    try {
				                    	//执行业务逻辑
				                        System.out.println(Thread.currentThread().getName()+"处理业务逻辑开始");
				                       for(int j=0;j<10000;j++){
				                           //System.out.println("处理业务逻辑"+j);
				                       }
				                       System.out.println(Thread.currentThread().getName()+"处理业务逻辑结束");
				                    } catch (Exception e) {
				                    	Thread.interrupted();
				                    } 
//				                    try {
//                                        barrier.await();
//                                    } catch (Exception e) {
//                                        // TODO Auto-generated catch block
//                                        e.printStackTrace();
//                                    } 
				                    System.out.println("线程："+Thread.currentThread().getName()+",耗时(s)："+(System.currentTimeMillis()-start)/1000);
				                    try {
                                        Thread.sleep(200);
                                    } catch (InterruptedException e) {
                                        
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                        
                                    }
				                }
				            };
				          pool.submit(synRunnable); 
				         
//				         if(i==1000) {//关闭线程
//			        	    shutdownAndAwaitTermination(pool);
//			        	    System.out.println("线程："+Thread.currentThread().getName()+" break;");
//			        	    break;
//				         }
					}
				}
			
			}).start();
    	}
    }
    
    
    public static void t3(){
                ExecutorService pool = Executors.newFixedThreadPool(4);
                final CyclicBarrier barrier  = new CyclicBarrier(4);
                    while(true) {
                     // 当前排队线程数
                        int queueSize = ((ThreadPoolExecutor)pool).getQueue().size();
                        System.out.println("当前排队线程数="+queueSize);
                        // 当前活动线程数
                        int activeCount = ((ThreadPoolExecutor)pool).getActiveCount();
//                      System.out.println(Thread.currentThread().getName()+"========================="+i);
                        long completedTaskCount = ((ThreadPoolExecutor)pool).getCompletedTaskCount();
                        // 总线程数（排队线程数 + 活动线程数 +  执行完成线程数） 
                        long taskCount = ((ThreadPoolExecutor)pool).getTaskCount();
//                      System.out.println("taskCount="+taskCount);
                           Runnable synRunnable = new Runnable() {
                                public void run() {
                                    long start = System.currentTimeMillis();
                                    try {
                                        //执行业务逻辑
                                        System.out.println(Thread.currentThread().getName()+"处理业务逻辑开始");
//                                        for(int i=0;i<100000;i++){
//                                            for(int j=0;j<100000;j++){
//                                                for(int k=0;k<100000;k++){
//                                                    
//                                                }  
//                                            }  
//                                        }
                                       System.out.println(Thread.currentThread().getName()+"处理业务逻辑结束");
                                       barrier.await();
                                    } catch (Exception e) {
                                        Thread.interrupted();
                                    } 
                                  try {
                                        barrier.await();
                                    } catch (Exception e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    } 
                                    System.out.println("线程："+Thread.currentThread().getName()+",耗时(s)："+(System.currentTimeMillis()-start)/1000);
                                    
                                }
                            };
                           
                          Future<?> submit = pool.submit(synRunnable); 
        }
    }
    
    /**
     * 关闭线程池
     * @param pool
     */
    public static   void shutdownAndAwaitTermination(ExecutorService pool) {
    	   pool.shutdown(); // Disable new tasks from being submitted
    	   try {
    	     // Wait a while for existing tasks to terminate
    	     if (!pool.awaitTermination(5000, TimeUnit.MILLISECONDS)) {
    	       pool.shutdownNow(); // Cancel currently executing tasks
    	       // Wait a while for tasks to respond to being cancelled
    	       if (!pool.awaitTermination(5000, TimeUnit.MILLISECONDS))
    	           System.err.println("Pool did not terminate");
    	     }
    	   } catch (InterruptedException ie) {
    	     // (Re-)Cancel if current thread also interrupted
    	     pool.shutdownNow();
    	     // Preserve interrupt status
    	     Thread.currentThread().interrupt();
    	   }
    	 }

    
	public static  Thread getThreadByName(String threadName) {
		for (Thread t : Thread.getAllStackTraces().keySet()) {
			
		if (t.getName().equals(threadName)) return t;
		}
		return null;
     }
    public static void main(String[] args) {
       t3();
    }
}

